/* ========================================================================= */
/* ------------------------------------------------------------------------- */
/*!
  \file			genopts.cc
  \date			Aug 2011
  \author		TNick

  \brief		Contains the implementation for GenOpts class


 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @n
 Please read ReadMe.txt and Licence.txt in root folder @n
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @n

*/
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
//
//
//
//
/*  INCLUDES    ------------------------------------------------------------ */

#include    <main.h>

#include    <QSettings>
#include    <QNetworkDiskCache>
#include    <QTimer>
#include    <QMenu>
#include    <QFileDialog>
#include    <QMessageBox>


#include	"genopts.h"
#include	"ui_genopts.h"
#include	"mainwindow.h"

#define XML_TAG_ROOT    "sellins_root"
#define XML_TAG_LIST    "target_list"
#define XML_TAG_LENTRY  "target_entry"


/*  INCLUDES    ============================================================ */
//
//
//
//
/*  CLASS    --------------------------------------------------------------- */

/* ------------------------------------------------------------------------- */
GenOpts::GenOpts	(QWidget *parent) :
	QMainWindow(parent),
	ui(new Ui::GenOpts)
{
	ui->setupUi(this);

	g_MW->readMe();
	ui->tx_Name->setText(g_MW->s_job_name);
	ui->sb_UpdateInterval->setValue(g_MW->msecs_to_sleep/1000); ;
	ui->tx_PathToScan->setText(g_MW->s_url_to_search);
	ui->tx_BaseUrl->setText(g_MW->s_url_base);
	ui->tx_PatternGroup->setPlainText(g_MW->s_group_pattern);
	ui->tx_PatternLink->setPlainText(g_MW->s_url_pattern);

	ui->tx_SaveLoc->setText(main_cache->cacheDirectory());

	ui->sb_Cache_size->setValue(main_cache->maximumCacheSize());

	//	ui->sb_Cached->setValue(g_MW->cached_count);
	//	ui->cb_SaveOld->setChecked(g_MW->saveToDisk());
	//	ui->cb_SaveOnlyPattern->setChecked(g_MW->savePatternOnly());
	g_MW->unlockMe();

	/* the menu for targets in a file */
	mnu_load = new QMenu(this);
	def_act = new QAction(this);
	def_act->setText(tr("(no file or no entries in specified file)"));

	QSettings settings;
	settings.beginGroup("Gen_opts");

	str_file_trg = settings.value("pos", QString()).toString();

	QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
	QSize size = settings.value("size", QSize(400, 300)).toSize();
	move(pos);
	resize(size);

	settings.endGroup();



	if (!str_file_trg.isEmpty())
		loadTargetFile();
	ui->loadQuerry->setMenu(mnu_load);

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
GenOpts::~GenOpts	(void)
{

	delete ui;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void			GenOpts::on_EntrySelected				(void)
{
	QAction * the_act = static_cast<QAction *>(sender());
	getEntry(the_act->text());
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void            GenOpts::on_buttonBox_accepted          (void)
{

	g_MW->writeMe();
	g_MW->msecs_to_sleep = 1000 *
			ui->sb_UpdateInterval->value();
	g_MW->s_job_name =
			ui->tx_Name->text().trimmed();
	if (g_MW->s_job_name.isEmpty())
		{
			g_MW->s_job_name = "(no name)";
		}
	g_MW->s_url_to_search =
			ui->tx_PathToScan->text();
	g_MW->s_url_base =
			ui->tx_BaseUrl->text();
	g_MW->s_group_pattern =
			ui->tx_PatternGroup->toPlainText();
	g_MW->s_url_pattern =
			ui->tx_PatternLink->toPlainText();
	main_cache->setCacheDirectory(
				ui->tx_SaveLoc->text());
	main_cache->setMaximumCacheSize(
				ui->sb_Cache_size->value());


	//	g_MW->cached_count =
	//			ui->sb_Cached->value();
	//	g_MW->setSaveToDisk(
	//				ui->cb_SaveOld->isChecked());
	//	g_MW->setSavePatternOnly(
	//				ui->cb_SaveOnlyPattern->isChecked());

	g_MW->unlockMe();

	g_MW->saveSettings();
	app_timer->setInterval(g_MW->msecs_to_sleep);

	close();
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void            GenOpts::loadTargetFile					(void)
{
	mnu_load->clear();
	for (;;)
		{
			QDomDocument * doc_xml = openXMLFile();
			if (doc_xml == NULL)
				break;

			QAction * new_act;
			QDomElement rootElement = doc_xml->firstChild().toElement();
			for(QDomNode node = rootElement.firstChild();
				!node.isNull();
				node = node.nextSibling())
				{
					if (node.nodeType() == QDomNode::TextNode)
						{
							QDomElement element = node.toElement();

                            if (element.tagName() == QString(XML_TAG_LIST))
								{
									for(QDomNode lst_node = element.firstChild();
										!lst_node.isNull();
										lst_node = lst_node.nextSibling())
										{
											QDomElement lst_element = lst_node.toElement();
                                            if (element.tagName() == QString(XML_TAG_LENTRY))
												{
													new_act = new QAction(this);
													new_act->setText(lst_element.tagName());
													connect(new_act, SIGNAL(triggered()),
															this, SLOT(on_EntrySelected()));
												}
										}
									break;
								}
						}
				}
			delete doc_xml;
		}

	mnu_load->addAction(def_act);
	return;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
QDomElement 	GenOpts::targetByName				(
	QDomDocument * doc_xml, QString s_name)
{
	QDomElement rootElement = doc_xml->firstChild().toElement();
	for(QDomNode node = rootElement.firstChild();
		!node.isNull();
		node = node.nextSibling())
		{
			if (node.nodeType() == QDomNode::TextNode)
				{
					QDomElement element = node.toElement();

                    if (element.tagName() == QString(XML_TAG_LIST))
						{
							for(QDomNode lst_node = element.firstChild();
								!lst_node.isNull();
								lst_node = lst_node.nextSibling())
								{
									QDomElement lst_element = lst_node.toElement();
                                    if (element.tagName() == QString(XML_TAG_LENTRY))
										{
											if (lst_element.text() == s_name)
												{/* this is the entry that we're looking for */
													return lst_element;
												}
										}
								}

							break;
						}
				}
		}

	return QDomElement();
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void		GenOpts::getEntry						(QString s_name)
{
	QDomDocument * doc_xml = openXMLFile();
	if (doc_xml == NULL)
		return;
	QDomElement trg_e = targetByName(doc_xml, s_name);
	if (trg_e.isNull())
		{
			QMessageBox::critical(
						this,
						QObject::tr("File error!!!"),
						QObject::tr("The file %1 does not have an target named %2.")
						.arg(str_file_trg)
						.arg(s_name)
						);
			delete doc_xml;
			return;
		}


	delete doc_xml;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void		GenOpts::on_loadQuerry_clicked			(void)
{

	QString fileName
			= QFileDialog::getOpenFileName(
				this,
				tr("Open XML file"),
				str_file_trg,
				tr("XML Files (*.xml)"));

	if (!fileName.isEmpty())
		{
			str_file_trg = fileName;
			loadTargetFile();
			mnu_load->exec();
		}

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
QDomDocument *	GenOpts::openXMLFile				(void)
{
	if (str_file_trg.isEmpty())
		{
			QMessageBox::critical(
						this,
						QObject::tr("File error!!!"),
						QObject::tr("No source file was specified.")
						);
			return NULL;
		}


	QFile xml_file(str_file_trg);
	if (xml_file.exists())
		{
			QMessageBox::critical(
						this,
						QObject::tr("File error!!!"),
						QObject::tr("The file %1 does not exists.")
						.arg(str_file_trg)
						);
			return NULL;
		}

	int errorLine, errorColumn;
	QString errorMsg;
	QDomDocument * doc_ret = new QDomDocument();
	if (!doc_ret->setContent(&xml_file, &errorMsg, &errorLine, &errorColumn))
		{
			QMessageBox::critical(
						this,
						QObject::tr("File error!!!"),
						QObject::tr("Syntax error in file %4, line %1, column %2:\n%3")
						.arg(errorLine)
						.arg(errorColumn)
						.arg(errorMsg)
						.arg(str_file_trg)
						);
			delete doc_ret;
			return NULL;

		}


	QDomElement rootElement = doc_ret->firstChild().toElement();
	if (rootElement.nodeType() != QDomNode::TextNode)
		{
			QMessageBox::critical(
						this,
						QObject::tr("XML file error!!!"),
						QObject::tr("The file %1 does not have proper format (%2).")
						.arg(str_file_trg)
						.arg(tr("root"))
						);
			delete doc_ret;
			return NULL;
		}
    if (rootElement.tagName() != QString(XML_TAG_ROOT))
		{
			QMessageBox::critical(
						this,
						QObject::tr("XML file error!!!"),
						QObject::tr("The file %1 does not have proper format (%2).")
						.arg(str_file_trg)
						.arg(tr("marker"))
						);
			delete doc_ret;
			return NULL;
		}

	return doc_ret;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void		GenOpts::on_saveQuerry_clicked				(void)
{
	QDomDocument * doc_xml = openXMLFile();
	if (doc_xml == NULL)
		{
			QString fileName
					= QFileDialog::getOpenFileName(
						this,
						tr("Select XML file"),
						str_file_trg,
						tr("XML Files (*.xml)"));
			if (!fileName.isEmpty())
				{
					str_file_trg = fileName;
                    doc_xml = new QDomDocument(XML_TAG_ROOT);
                    if (doc_xml == NULL)
                        return;

                    QDomElement root = doc_xml->createElement(XML_TAG_ROOT);
                    doc.appendChild(root);

                    QDomElement tag = doc_xml->createElement(XML_TAG_LIST);
                    root.appendChild(tag);

				}
		}

    /* check if this name is already inside */
    QDomElement our_tag = targetByName(doc_xml, ui->tx_Name->text());
    if (!our_tag.isNull())
        {
            our_tag.
        }
	delete doc_xml;

}
/* ========================================================================= */

/*  CLASS    =============================================================== */
//
//
//
//
/* ------------------------------------------------------------------------- */
/* ========================================================================= */



